#include <gtest\gtest.h>
#include <connection\message.h>
#include <connection\proto_message.h>
#include <connection\message_proto_typedef.h>
#include "test_message_proto.pb.h"

namespace cs
{

namespace constant
{
	const uint32_t msg_id = 0x30;
	const address sender = 0x01;
	const address receiver = 0x02;
	const size_t empty_msg_size = 0;

	const char parsed_header [message::header_length] = 
		{0, 0, 0, 0, 0, 48, 0, 1, 0, 2};

	const std::string empty_str("");
	const std::string dummy("dummy");
}

TEST(ut_message, encode_header)
{
	message msg(constant::msg_id, constant::sender,
		constant::receiver);
	const std::string str_msg = msg;

	EXPECT_EQ(str_msg, std::string(constant::parsed_header, message::header_length));
	EXPECT_EQ(msg.id(), constant::msg_id);
	EXPECT_EQ(msg.sender(), constant::sender);
	EXPECT_EQ(msg.receiver(), constant::receiver);
	EXPECT_EQ(msg.get(), constant::empty_str);
	EXPECT_EQ(msg.size(), constant::empty_msg_size);
}

TEST(ut_message, decode_hader)
{
	message msg;
	memcpy(msg.get_header().data(), constant::parsed_header, message::header_length);
	msg.decode_header();

	EXPECT_EQ(msg.id(), constant::msg_id);
	EXPECT_EQ(msg.sender(), constant::sender);
	EXPECT_EQ(msg.receiver(), constant::receiver);
	EXPECT_EQ(msg.size(), constant::empty_msg_size);
}

TEST(ut_message, encode_header_empty_msg)
{
	message msg(constant::msg_id, constant::sender, 
		constant::receiver, constant::empty_str);
	const std::string str_msg = msg;

	EXPECT_EQ(str_msg, std::string(constant::parsed_header, message::header_length));
	EXPECT_EQ(msg.id(), constant::msg_id);
	EXPECT_EQ(msg.sender(), constant::sender);
	EXPECT_EQ(msg.receiver(), constant::receiver);
	EXPECT_EQ(msg.get(), constant::empty_str);
	EXPECT_EQ(msg.size(), constant::empty_msg_size);
}

TEST(ut_message, proto_msg)
{
	GOOGLE_PROTOBUF_VERIFY_VERSION;
	
	proto_message<test_message_proto> pmsg;
	pmsg->set_name(constant::dummy);

	message msg(constant::msg_id, constant::sender, 
		constant::receiver, pmsg.serialize());

	EXPECT_EQ(msg.id(), constant::msg_id);
	EXPECT_EQ(msg.sender(), constant::sender);
	EXPECT_EQ(msg.receiver(), constant::receiver);
	EXPECT_TRUE(msg.serialize().size() > constant::empty_msg_size);

	proto_message<test_message_proto> received_pmsg(msg.get());

	EXPECT_TRUE(received_pmsg.is_valid());
	EXPECT_EQ(received_pmsg->name(), pmsg->name());

	google::protobuf::ShutdownProtobufLibrary();
}

}